<?php
/**
 * Created by PhpStorm.
 * User: Giles
 * Date: 2017/7/19
 * Time: 18:04
 */
namespace Home\Controller;

class DownController extends BaseController
{
    public function index()
    {
        $fileName = I('get.file');
        //$filePath = realpath($fileName);
        //var_dump($fileName);exit;
        $fp = fopen($fileName, 'rb');

        if(!$fp){
            header('HTTP/1.1 404 Not Found');
            echo "Error: 404 Not Found.";
            exit;
        }

        //$fileName = $fileName;
        $encoded_filename = urlencode($fileName);
        $encoded_filename = str_replace("+", "%20", $encoded_filename);

        header('HTTP/1.1 200 OK');
        header( "Pragma: public" );
        header( "Expires: 0" );
        header("Content-type: application/octet-stream");
        header("Content-Length: " . filesize($fileName));
        header("Accept-Ranges: bytes");
        header("Accept-Length: " . filesize($fileName));

        $ua = $_SERVER["HTTP_USER_AGENT"];
        if (preg_match("/MSIE/", $ua)) {
            header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
        } else if (preg_match("/Firefox/", $ua)) {
            header('Content-Disposition: attachment; filename*="utf8\'\'' . $fileName . '"');
        } else {
            header('Content-Disposition: attachment; filename="' . $fileName . '"');
        }

        ob_end_clean(); //有些情况可能需要调用此函数

        // 输出文件内容
        fpassthru($fp);
        exit;
    }
}